﻿using System;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using ent;

public partial class main_content : System.Web.UI.Page {
    public String URL = ApplicationCommon.getPageThis();
    public String URL_STYLESHEET = "~/css/style.aspx";
    public String URL_CONTROLPANEL_POSTS = "~/controlpanel/contents_crud.aspx";
    public String URL_USER_ACCOUNT = "~/main/register_user_account.aspx";

    private String _qsMode = String.Empty;
    private String _qsContentHeaderSlug = String.Empty;

    private int _qsId = 0;
    private int _qsIdParent = 0;
    private int _qsIdStyle = 0;
    private int _qsIdTemplate = 0;
    private int _qsType = 0;

    private bool _permitManagement = false;

    private TableUsers t1 = new TableUsers();
    private TableContents t2 = new TableContents();
    private TableLists t3 = new TableLists();
    private ServiceContents s1 = new ServiceContents();

    protected override void OnLoad(EventArgs e) {
        base.OnLoad(e);
        this.Page.Header.DataBind();
    }
    protected void Page_Load(Object sender, EventArgs e) {
        _qsMode = Request.QueryString["mode"];
        _qsId = System.Convert.ToInt32(Request.QueryString["id"]);
        _qsContentHeaderSlug = getQueryStringContentHeader();
        getRequestJavaScript();

        // Authenticate.
        authenticateUser();
        // Mode.
        if(String.Equals(_qsMode, "add") && _qsId > 0) {
            viewAdd();
        } else {
            viewCrud();
        }
    }

#region Methods

    /// <summary>Authenticate user.</summary>
    protected void authenticateUser() {
        if(!ApplicationCommon.isValidSession(Session)) {
            _permitManagement = false;
        } else {
            _permitManagement = true;
        }
    }
    /// <summary>Get content header from various query strings.</summary>
    protected String getQueryStringContentHeader() {
        if(!ApplicationCommon.isEmpty(Request.QueryString["header"])) {
            return Request.QueryString["header"];
        } else if(!ApplicationCommon.isEmpty(Request.QueryString["title"])) {
            return Request.QueryString["title"];
        } else if(!ApplicationCommon.isEmpty(Request.QueryString["name"])) {
            return Request.QueryString["name"];
        } else if(!ApplicationCommon.isEmpty(Request.QueryString["slug"])) {
            return Request.QueryString["slug"];
        } else {
            return String.Empty;
        }
    }
    /// <summary>Get HTTP request from JavaScript postback.</summary>
    protected void getRequestJavaScript() {
        if(!Page.IsPostBack) {return;}

        String eventName = Request.Form["__EVENTTARGET"];
        String eventArgument = Request.Form["__EVENTARGUMENT"];

        if(String.Equals(eventName, "onMode")) {
            // Set mode by query string.
            if(String.Equals(eventArgument, "add")) {
                Hashtable qs1 = new Hashtable();
                qs1.Add("mode", "add");
                Response.Redirect(ApplicationCommon.setQueryString(qs1, URL));
            } else {
                Response.Redirect(URL);
            }
        }
    }
    /// <summary>Init form input values.</summary>
    protected void initFormInputValues() {
        // First load data for manipulation before postback.
        if(!Page.IsPostBack) {
            // Get list.
            ucContent.prop_ddlType.DataSource = t3.getList((int)TableLists.enumList.ContentTypes, null);
            ucContent.prop_ddlType.DataTextField = TableLists.TBL__lists__list_name;
            ucContent.prop_ddlType.DataValueField = TableLists.TBL__lists__list_value;
            ucContent.prop_ddlType.DataBind();
            // Get list.
            ucContent.prop_ddlStatus.DataSource = t3.getList((int)TableLists.enumList.ContentStatuses, null);
            ucContent.prop_ddlStatus.DataTextField = TableLists.TBL__lists__list_name;
            ucContent.prop_ddlStatus.DataValueField = TableLists.TBL__lists__list_value;
            ucContent.prop_ddlStatus.DataBind();
        }
    }
    /// <summary>View in CRUD mode.</summary>
    protected void viewCrud() {
        DataTable dt1;

        if(_qsId > 0 || !ApplicationCommon.isEmpty(_qsContentHeaderSlug)) {
            // Get records from query string by id or slug.
            if(!ApplicationCommon.isEmpty(_qsContentHeaderSlug)) {
                dt1 = s1.getContentsExtendedBySlug(_qsContentHeaderSlug);
            } else {
                dt1 = s1.getContentsExtended(_qsId);
            }
            if(dt1.Rows.Count > 0) {
                viewCrudStateWrapperBegin(ref dt1);
                // Change logic by type.
                switch(_qsType) {
                    case (int)TableLists.enumContentType.Page:
                    case (int)TableLists.enumContentType.Post:
                        rptrContent.DataSource = dt1;
                        rptrContent.DataBind();
                        break;
                    case (int)TableLists.enumContentType.Blog:
                        rptrContent.DataSource = s1.getContentsByParent(_qsId);
                        rptrContent.DataBind();
                        break;
                    case (int)TableLists.enumContentType.System:
                        // Is feed RSS type. [[feed:http://www.example.com/feed/]]
                        String strUrl = t2.getFeedUrls(HttpUtility.HtmlDecode((String)dt1.Rows[0][TableContents.TBL__contents__content_body]))[0];
                        if(!ApplicationCommon.isEmpty(strUrl)) {
                            main_content_feed ucContentFeed = (main_content_feed)Page.LoadControl("~/main/content_feed.ascx");
                            ucContentFeed.ID = "ucContentFeed";
                            plhCrud.Controls.Add(ucContentFeed);

                            DataSet ds1 = s1.getFeed(strUrl);
                            DataTable dtAtomSummary = ds1.Tables[4];
                            // Debug feed.
                            //ucContentFeed.prop_gvFeed.DataSource = ds1.Tables[2];
                            //ucContentFeed.prop_gvFeed.DataBind();
                            // Set feed.
                            ucContentFeed.prop_rptrFeed.DataSource = DatabaseCommon.truncateDataTable(ds1.Tables[2], 8);
                            ucContentFeed.prop_rptrFeed.DataBind();
                        }
                        break;
                }
                viewCrudStateWrapperEnd(ref dt1);
            } else {
                dt1.ImportRow(t2.getContent(_qsId));
                plhCrud.Visible = true;
                lnkContentAdd.Visible = true;
                lnkContentAdd.CommandName = "new";
                setContentHeader(dt1);
                if(_permitManagement) {
                    pnlPageControlPanel.Visible = true;
                    setPageControlPanel(dt1);
                }
                lblError.Text = "No records found.";
            }
        } else {
            lblError.Text = "Query strings are missing or invalid.";
        }
    }
    /// <summary>View in add mode.</summary>
    protected void viewAdd() {
        plhAdd.Visible = true;
        plhJavaScriptTextEditor.Visible = true;
        plhJavaScriptAdd.Visible = true;
        // Set form.
        ucContent.prop_pnlType.Visible = false;
        ucContent.prop_txtTitle.Focus();
        ucContent.prop_pnlHeader.Visible = false;
        ucContent.prop_pnlFooter.Visible = false;
        ucContent.prop_rowStatus.Visible = true;
        ucContent.prop_rowStyle.Visible = false;
        ucContent.prop_rowTemplate.Visible = false;
        ucContent.prop_rowOrder.Visible = true;
        ucContent.prop_rowOrderType.Visible = false;
        ucContent.prop_rowMenuOrder.Visible = false;
        // Init form input values.
        initFormInputValues();
        // First load data for manipulation before postback.
        if(!Page.IsPostBack) {
            ucContent.prop_ddlStatus.Items.FindByValue(((int)TableLists.enumContentStatus.Publish).ToString()).Selected = true;
        }
    }
    /// <summary>Set content header.</summary>
    protected void setContentHeader(DataTable dt1) {
        // Set page title and link.
        Hashtable qs2 = new Hashtable();
        qs2.Add("id", _qsId);
        this.Header.Title = (String)dt1.Rows[0][TableContents.TBL__contents__content_title];
        hypPageTitle.NavigateUrl = ApplicationCommon.setQueryString(qs2, URL);
        hypPageTitle.Text = (String)dt1.Rows[0][TableContents.TBL__contents__content_title];
    }
    /// <summary>Set page control panel.</summary>
    protected void setPageControlPanel(DataTable dt1) {
        // Set page control panel, prepend.
        String strPageControlPanelPrepend = String.Empty;
        strPageControlPanelPrepend += "Content ID: <span class=\"bold\">" + dt1.Rows[0][TableContents.TBL__contents__content_id].ToString() + "</span>";
        strPageControlPanelPrepend += " | ";
        strPageControlPanelPrepend += "Content Type: <span class=\"bold\" id=\"ajax-page-type\">" + dt1.Rows[0][TableContents.TBL__contents__content_type].ToString() + " " + t3.getItemName((int)TableLists.enumList.ContentTypes, (int)dt1.Rows[0][TableContents.TBL__contents__content_type]) + "</span>";
        lblControlPanelPrepend.Text = strPageControlPanelPrepend;
        // Set page control panel, append.
        String strPageControlPanelAppend = String.Empty;
        int intPageAssignedToId = (int)dt1.Rows[0][TableContents.TBL__contents__content_assignedto];
        strPageControlPanelAppend += "Content Assigned To: <span class=\"bold\">" + intPageAssignedToId;
        if(intPageAssignedToId > 0) {
            strPageControlPanelAppend += " " + t1.getUserHumanName(intPageAssignedToId);
        } else {
            strPageControlPanelAppend += " " + Enum.GetName(typeof(ApplicationCommon.enumRole), TableLists.getRoleByAssignedTo(intPageAssignedToId));
        }
        strPageControlPanelAppend += "</span>";
        if(lnkContentAdd.Visible || lnkContentEditSpecial.Visible) {
            strPageControlPanelAppend += " | ";
        }
        lblControlPanelAppend.Text = strPageControlPanelAppend;
    }

#endregion

#region States

    /// <summary>Begin of wrapper state for view in CRUD mode.</summary>
    protected void viewCrudStateWrapperBegin(ref DataTable dt1) {
        _qsId = (int)dt1.Rows[0][TableContents.TBL__contents__content_id];
        _qsIdParent = (int)dt1.Rows[0][TableContents.TBL__contents__content_parent_id];
        _qsContentHeaderSlug = (String)dt1.Rows[0][TableContents.TBL__contents__content_title_slug];
        _qsIdStyle = (int)dt1.Rows[0][TableContents.TBL__contents__content_style_id];
        _qsIdTemplate = (int)dt1.Rows[0][TableContents.TBL__contents__content_template_id];
        _qsType = (int)dt1.Rows[0][TableContents.TBL__contents__content_type];

        // Reauthenticate user based on content.
        if(_permitManagement) {
            _permitManagement = TableContents.authenticateUserByContent(_permitManagement, (int)dt1.Rows[0][TableContents.TBL__contents__content_assignedto], Session);
        }

        // Enable visibility.
        plhCrud.Visible = true;

        // Merge template to a post for single type page.
        if(_qsIdTemplate > 0 && _qsType == (int)TableLists.enumContentType.Page) {
            // Get and set body for ajax.
            dt1.Rows[0][TableContents.TBL__contents__content_body] = "<span class=\"ajax-post-body-inner\">" + dt1.Rows[0][TableContents.TBL__contents__content_body] + "</span>";
            // Merge content to body.
            DataRow dr1 = s1.getContent(_qsIdTemplate);
            dt1.Rows[0][TableContents.TBL__contents__content_body] = HttpUtility.HtmlDecode(getTemplateAndMergeContent(HttpUtility.HtmlDecode((String)dr1[TableContents.TBL__contents__content_body]), (String)dt1.Rows[0][TableContents.TBL__contents__content_body]));
        }

        // Merge style to all record type posts.
        if(_qsIdStyle > 0) {
            plhPageStyle.Visible = true;
            plhPageStyle.Controls.Add(new LiteralControl("<link href=\"" + ResolveClientUrl(URL_STYLESHEET + "?id=" + _qsIdStyle) + "\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\"/>"));
        }

        // Modify data base on type.
        switch(_qsType) {
            case (int)TableLists.enumContentType.Page:
                dt1 = DatabaseCommon.truncateDataTable(dt1, 1);
                break;
        }
        // Set page title and link.
        setContentHeader(dt1);
    }
    /// <summary>End of wrapper state for view in CRUD mode.</summary>
    protected void viewCrudStateWrapperEnd(ref DataTable dt1) {
        if(_permitManagement) {
            Master.prop_plhHeadYui.Visible = true;
            plhClientScript.Visible = true;
            plhJavaScriptTextEditor.Visible = true;
            plhJavaScriptCrud.Visible = true;
            pnlPageControlPanel.Visible = true;
            // Change form base on type.
            switch(_qsType) {
                case (int)TableLists.enumContentType.Page:
                    lnkContentEditSpecial.Visible = true;
                    break;
                case (int)TableLists.enumContentType.Blog:
                    lnkContentAdd.Visible = true;
                    break;
                case (int)TableLists.enumContentType.Post:
                    lnkContentEditSpecial.Visible = true;
                    break;
            }
            // Set page control panel.
            setPageControlPanel(dt1);
        }
    }

#endregion

#region Events

    protected void rptrContent_ItemDataBound(Object sender, RepeaterItemEventArgs e) {
        // This event is raised for the header, the footer, separators, and items.
        if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
            DataRowView drv1 = (DataRowView)e.Item.DataItem;

            // Validate type. If invalid, then return.
            if((int)drv1[TableContents.TBL__contents__content_type] != (int)TableLists.enumContentType.Page && (int)drv1[TableContents.TBL__contents__content_type] != (int)TableLists.enumContentType.Post) {
                ((Panel)e.Item.FindControl("pnlOutput")).Visible = false;
                return;
            }

            // Set header.
            HyperLink hypContentTitle = ((HyperLink)e.Item.FindControl("hypContentTitle"));
            Hashtable qs1 = new Hashtable();
            qs1.Add("id", drv1[TableContents.TBL__contents__content_id].ToString());
            hypContentTitle.NavigateUrl = ApplicationCommon.setQueryString(qs1, URL);
            hypContentTitle.Text = (String)drv1[TableContents.TBL__contents__content_title];
            if(_qsType == (int)TableLists.enumContentType.Page || _qsType == (int)TableLists.enumContentType.Post) {
                ((HtmlGenericControl)e.Item.FindControl("hgcContentTitle")).Style["display"] = "none";
            }
            // Set status.
            String s1 = String.Empty;
            if(_permitManagement) {
                s1 += "Status: <span>" + drv1[TableContents.TBL__contents__content_status].ToString() + " " + t3.getItemName((int)TableLists.enumList.ContentStatuses, (int)drv1[TableContents.TBL__contents__content_status]) + "</span>";
                s1 += " &bull; ";
                s1 += "Created: <span>" + ((DateTime)drv1[TableContents.TBL__contents__content_date_created]).ToShortDateString() + "</span>";
                s1 += " &bull; ";
            }
            if(!(drv1[TableContents.TBL__contents__content_date_published] is DBNull)) {
                s1 += "Published: <span>" + ((DateTime)drv1[TableContents.TBL__contents__content_date_published]).ToShortDateString() + "</span>";
            } else {
                s1 += "Published: <span>" + "None" + "</span>";
            }
            s1 += " &bull; ";
            s1 += "Modified: <span>" + ((DateTime)drv1[TableContents.TBL__contents__content_date_modified]).ToString() + "</span>";
            ((Label)e.Item.FindControl("lblContentStatus")).Text = s1;
            // Set body.
            if(_qsIdTemplate > 0 && _qsType == (int)TableLists.enumContentType.Page) {
                ((Label)e.Item.FindControl("lblContentBody")).Text = (String)drv1[TableContents.TBL__contents__content_body];
            } else {
                ((Label)e.Item.FindControl("lblContentBody")).Text = "<span class=\"ajax-content-body-inner\">" + HttpUtility.HtmlDecode((String)drv1[TableContents.TBL__contents__content_body]) + "</span>";
            }

            if(_permitManagement) {
                // Set edit panel.
                Panel pnlEdit = ((Panel)e.Item.FindControl("pnlEdit"));
                pnlEdit.Visible = true;

                // Set edit form.
                form_content ucContent_Ajax = ((form_content)e.Item.FindControl("ucContent_Ajax"));
                ucContent_Ajax.prop_pnlType.Visible = false;
                ucContent_Ajax.prop_pnlHeader.Style["display"] = "none";
                ucContent_Ajax.prop_pnlFooter.Style["display"] = "none";
                ucContent_Ajax.prop_pnlMeta.Style["display"] = "none";
                ucContent_Ajax.prop_rowStatus.Visible = false;
                ucContent_Ajax.prop_rowStyle.Visible = false;
                ucContent_Ajax.prop_rowTemplate.Visible = false;
                ucContent_Ajax.prop_rowOrder.Visible = true;
                ucContent_Ajax.prop_rowOrderType.Visible = false;
                ucContent_Ajax.prop_rowMenuOrder.Visible = false;

                // Set control panel.
                ((Panel)e.Item.FindControl("pnlContentControlPanel")).Visible = true;
                ((Label)e.Item.FindControl("lblContentId")).Text = "Content ID: <span class=\"bold ajax-content-id\">" + drv1[TableContents.TBL__contents__content_id].ToString() + "</span>";
                ((Label)e.Item.FindControl("lblContentType")).Text = "Content Type: <span class=\"bold ajax-content-contenttype\">" + drv1[TableContents.TBL__contents__content_type].ToString() + " " + t3.getItemName((int)TableLists.enumList.ContentTypes, (int)drv1[TableContents.TBL__contents__content_type]) + "</span>";
                ((Label)e.Item.FindControl("lblOrder")).Text = "Order: <span class=\"bold ajax-content-order\">" + drv1[TableContents.TBL__contents__content_order].ToString() + "</span>";
                ((Label)e.Item.FindControl("lblAuthorUserId")).Text = "Author User ID: <span class=\"bold\">" + drv1[TableContents.TBL__contents__content_author_user_id].ToString() + "</span>";
                ((Label)e.Item.FindControl("lblAuthorUserId")).ToolTip = t1.getUserHumanName((int)drv1[TableContents.TBL__contents__content_author_user_id]);
                ((Label)e.Item.FindControl("lblEditorUserId")).Text = "Editor User ID: <span class=\"bold\">" + drv1[TableContents.TBL__contents__content_editor_user_id].ToString() + "</span>";
                ((Label)e.Item.FindControl("lblEditorUserId")).ToolTip = t1.getUserHumanName((int)drv1[TableContents.TBL__contents__content_editor_user_id]);
                HyperLink hypEdit = ((HyperLink)e.Item.FindControl("hypEdit"));
                hypEdit.NavigateUrl = "#";
                hypEdit.Attributes["onclick"] = "clsThis.onEdit(this,'" + ((Panel)e.Item.FindControl("pnlOutput")).ClientID + "', '" + pnlEdit.ClientID + "', " + (int)Session[ApplicationCommon.SESSION__user_id] + ");return false;";
            }
        }
    }
    protected void rptrContent_ItemCommand(Object sender, RepeaterCommandEventArgs e) { }
    protected void lnkContentAdd_Command(Object sender, CommandEventArgs e) {
        Hashtable qs1 = new Hashtable();
        qs1.Add("mode", "add");
        qs1.Add("id", _qsId);
        if(String.Equals(e.CommandName, "new")) {
            qs1.Add("return", HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl));
            Response.Redirect(ApplicationCommon.setQueryString(qs1, URL_CONTROLPANEL_POSTS));
        } else if(String.Equals(e.CommandName, "add")) {
            Response.Redirect(ApplicationCommon.setQueryString(qs1, URL));
        }
    }
    protected void lnkContentEditSpecial_Click(Object sender, EventArgs e) {
        Hashtable qs1 = new Hashtable();
        qs1.Add("mode", "edit");
        qs1.Add("id", _qsId);
        qs1.Add("return", HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl));
        Response.Redirect(ApplicationCommon.setQueryString(qs1, URL_CONTROLPANEL_POSTS));
    }
    protected void btnAddOkay_Click(Object sender, EventArgs e) {
        if(plhAdd.Visible) {
            Hashtable p1 = new Hashtable();
            p1.Add(TableContents.TBL__contents__content_author_user_id, (int)Session[ApplicationCommon.SESSION__user_id]);
            p1.Add(TableContents.TBL__contents__content_editor_user_id, (int)Session[ApplicationCommon.SESSION__user_id]);
            p1.Add(TableContents.TBL__contents__content_type, (int)TableLists.enumContentType.Post);
            p1.Add(TableContents.TBL__contents__content_parent_id, _qsId);
            p1.Add(TableContents.TBL__contents__content_title, ucContent.prop_txtTitle.Text);
            p1.Add(TableContents.TBL__contents__content_title_slug, TableContents.toSlug(ucContent.prop_txtTitle.Text));
            p1.Add(TableContents.TBL__contents__content_header, ucContent.prop_txtHeader.Text);
            p1.Add(TableContents.TBL__contents__content_body, ucContent.prop_txtBody.Text);
            p1.Add(TableContents.TBL__contents__content_footer, ucContent.prop_txtFooter.Text);
            p1.Add(TableContents.TBL__contents__content_status, ucContent.prop_ddlStatus.SelectedValue);
            p1.Add(TableContents.TBL__contents__content_order, ucContent.prop_txtOrder.Text);
            if(System.Convert.ToInt32(ucContent.prop_ddlStatus.SelectedValue) == (int)TableLists.enumContentStatus.Publish) {
                p1.Add(TableContents.TBL__contents__content_date_published, DateTime.Now);
            }
            p1.Add(TableContents.TBL__contents__content_date_modified, DateTime.Now);
            p1.Add(TableContents.TBL__contents__content_date_created, DateTime.Now);
            t2.createContent(p1);
        }
        Hashtable qs1 = new Hashtable();
        qs1.Add("id", _qsId);
        Response.Redirect(ApplicationCommon.setQueryString(qs1, URL));
    }
    protected void btnAddCancel_Click(Object sender, EventArgs e) {
        Hashtable qs1 = new Hashtable();
        qs1.Add("id", _qsId);
        Response.Redirect(ApplicationCommon.setQueryString(qs1, URL));
    }

#endregion

#region Special

    /// <summary>Get template and merge content.</summary>
    protected String getTemplateAndMergeContent(String template, String content) {
        // Parse template.
        ApplicationTemplateParser tplParser = new ApplicationTemplateParser(template, "<!--BEGIN:", "-->", "<!--END:", "-->");
        if(!tplParser.Build()) {
            return null;
        }

        // Parse blocks and assign content.
        ITmplBlock tplFormat1 = tplParser.ParseBlock("FORMAT1");
        tplFormat1.Assign("INNER1", content);
        tplFormat1.Out();

        // Get document block.
        ITmplBlock tplDoc = tplParser.ParseBlock();
        tplDoc.Out();

        // Return merged content.
        return tplDoc.BlockString;
    }

#endregion

}